package com.markhsiu.main;

import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class CompressUtils {

	private static final ThreadLocal<Deflater> compressorLocal = new ThreadLocal<>();
	private static final ThreadLocal<Inflater> decompressorLocal = new ThreadLocal<>();

	public static byte[] compress(byte input[]) {
		byte[] buf = new byte[input.length];
		int count = compress(input, 0, input.length, buf, 0, buf.length);
		byte[] copy = new byte[count];
		System.arraycopy(buf, 0, copy, 0, count);
		return copy;
	}

	public static int compress(final byte input[], int inOffset, int inLen, final byte output[], int outOffset, int outLen) {
		Deflater compressor = compressorLocal.get();
		if (compressor == null) {
			compressor = new Deflater(1);
			compressorLocal.set(compressor);
		}

		compressor.setInput(input, inOffset, inLen);
		compressor.finish();
		int count = 0;
		count = compressor.deflate(output, outOffset, outLen - outOffset);
		compressor.reset();
		return count;

	}

	public static int uncompress(final byte[] input, int inOffset, int inLen, final byte[] output) throws DataFormatException {
		Inflater decompressor = decompressorLocal.get();
		if(decompressor == null){
			decompressor = new Inflater();
			decompressorLocal.set(decompressor);
		}
	 
		decompressor.setInput(input, inOffset, inLen);
		int count = decompressor.inflate(output);
		decompressor.reset();
		return count;
	}

	 

}
